package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 零售管理控制器
 * @date: 2025/8/11 10:44
 * @author: ftt
 */
@RestController
@RequestMapping("retail")
public class RetailController {
    
    private static final Logger log = LoggerFactory.getLogger(RetailController.class);
    
    @Autowired
    private RetailOutboundService retailOutboundService;
    
    @Autowired
    private RetailOutboundItemService retailOutboundItemService;
    
    @Autowired
    private RetailReturnService retailReturnService;
    
    @Autowired
    private RetailReturnItemService retailReturnItemService;
    
    @Autowired
    private MemberService memberService;
    
    @Autowired
    private WarehouseService warehouseService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private StockService stockService;
    
    // ==================== 基础数据（会员） ====================

    /**
     * 获取会员列表（用于前端下拉）
     */
    @GetMapping("/members")
    public List<Member> getMemberList() {
        return memberService.list();
    }

    // ==================== 零售出库管理 ====================
    
    /**
     * 分页查询零售出库单
     */
    @GetMapping("/outbound/page")
    public Page<RetailOutbound> getRetailOutboundPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String outboundNo,
            @RequestParam(required = false) Long memberId,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Page<RetailOutbound> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<RetailOutbound> wrapper = Wrappers.lambdaQuery();
        
        if (StringUtils.hasText(outboundNo)) {
            wrapper.like(RetailOutbound::getOutboundNo, outboundNo);
        }
        if (memberId != null) {
            wrapper.eq(RetailOutbound::getMemberId, memberId);
        }
        if (warehouseId != null) {
            wrapper.eq(RetailOutbound::getWarehouseId, warehouseId);
        }
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(RetailOutbound::getOutboundDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(RetailOutbound::getOutboundDate, endDate);
        }
        
        wrapper.orderByDesc(RetailOutbound::getCreateTime);
        Page<RetailOutbound> page1 = retailOutboundService.page(page, wrapper);
        List<RetailOutbound> records = page1.getRecords();
        
        for (RetailOutbound record : records) {
            // 设置仓库名称
            if (record.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(record.getWarehouseId());
                if (warehouse != null) {
                    record.setWarehouseName(warehouse.getName());
                }
            }
            
            // 设置会员名称
            if (record.getMemberId() != null) {
                Member member = memberService.getById(record.getMemberId());
                if (member != null) {
                    record.setMemberName(member.getName());
                }
            }
        }
        
        return page1;
    }
    
    /**
     * 创建零售出库单
     */
    @PostMapping("/outbound")
    public RetailOutbound createRetailOutbound(@RequestBody RetailOutbound retailOutbound) {
        try {
            // 设置创建时间和状态
            retailOutbound.setCreateTime(new Date());
            if (retailOutbound.getStatus() == null) {
                retailOutbound.setStatus(0); // 默认为草稿状态
            }
            
            // 生成零售出库单号
            if (retailOutbound.getOutboundNo() == null || retailOutbound.getOutboundNo().isEmpty()) {
                retailOutbound.setOutboundNo(generateRetailOutboundNo());
            }
            
            // 保存零售出库单
            retailOutboundService.save(retailOutbound);
            
            // 保存商品明细
            if (retailOutbound.getItems() != null && !retailOutbound.getItems().isEmpty()) {
                for (RetailOutboundItem item : retailOutbound.getItems()) {
                    item.setOutboundId(retailOutbound.getId());
                    retailOutboundItemService.save(item);
                }
            }
            
            return retailOutbound;
        } catch (Exception e) {
            log.error("创建零售出库单失败", e);
            throw new RuntimeException("创建零售出库单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新零售出库单
     */
    @PutMapping("/outbound")
    public RetailOutbound updateRetailOutbound(@RequestBody RetailOutbound retailOutbound) {
        try {
            // 更新零售出库单基本信息
            retailOutboundService.updateById(retailOutbound);
            
            // 更新商品明细
            if (retailOutbound.getItems() != null) {
                // 删除原有明细
                retailOutboundItemService.remove(new QueryWrapper<RetailOutboundItem>()
                    .eq("outbound_id", retailOutbound.getId()));
                
                // 保存新的明细
                for (RetailOutboundItem item : retailOutbound.getItems()) {
                    item.setOutboundId(retailOutbound.getId());
                    retailOutboundItemService.save(item);
                }
            }
            
            return retailOutbound;
        } catch (Exception e) {
            log.error("更新零售出库单失败", e);
            throw new RuntimeException("更新零售出库单失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除零售出库单
     */
    @DeleteMapping("/outbound/{id}")
    public boolean deleteRetailOutbound(@PathVariable Long id) {
        try {
            // 删除零售出库单明细
            retailOutboundItemService.remove(new QueryWrapper<RetailOutboundItem>()
                    .eq("outbound_id", id));
            // 删除零售出库单
            return retailOutboundService.removeById(id);
        } catch (Exception e) {
            log.error("删除零售出库单失败", e);
            return false;
        }
    }
    
    /**
     * 完成零售出库单
     */
    @PutMapping("/outbound/complete/{id}")
    public boolean completeRetailOutbound(@PathVariable Long id) {
        try {
            // 获取零售出库单详情
            RetailOutbound retailOutbound = retailOutboundService.getById(id);
            if (retailOutbound == null) {
                log.error("零售出库单不存在: {}", id);
                return false;
            }
            
            // 检查零售出库单状态
            if (retailOutbound.getStatus() != 1) {
                log.error("零售出库单状态不正确，无法完成: id={}, status={}", id, retailOutbound.getStatus());
                return false;
            }
            
            // 获取商品明细
            List<RetailOutboundItem> items = retailOutboundItemService.lambdaQuery()
                    .eq(RetailOutboundItem::getOutboundId, id)
                    .list();
            
            if (items == null || items.isEmpty()) {
                log.error("零售出库单没有商品明细: {}", id);
                return false;
            }
            
            // 调整库存（减少库存）
            for (RetailOutboundItem item : items) {
                if (!adjustStock(item.getProductId(), retailOutbound.getWarehouseId(), item.getQuantity().negate())) {
                    log.error("调整商品库存失败: productId={}, warehouseId={}, quantity={}", 
                        item.getProductId(), retailOutbound.getWarehouseId(), item.getQuantity());
                    return false;
                }
            }
            
            // 更新零售出库单状态为已完成
            retailOutbound.setStatus(2);
            retailOutboundService.updateById(retailOutbound);
            
            log.info("零售出库单完成成功: {}", id);
            return true;
        } catch (Exception e) {
            log.error("完成零售出库单失败: {}", id, e);
            return false;
        }
    }
    
    /**
     * 获取零售出库单详情（包含明细）
     */
    @GetMapping("/outbound/withDetails/{id}")
    public RetailOutbound getRetailOutboundWithDetails(@PathVariable Long id) {
        RetailOutbound retailOutbound = retailOutboundService.getById(id);
        if (retailOutbound != null) {
            // 设置仓库名称
            if (retailOutbound.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(retailOutbound.getWarehouseId());
                if (warehouse != null) {
                    retailOutbound.setWarehouseName(warehouse.getName());
                }
            }
            
            // 设置会员名称
            if (retailOutbound.getMemberId() != null) {
                Member member = memberService.getById(retailOutbound.getMemberId());
                if (member != null) {
                    retailOutbound.setMemberName(member.getName());
                }
            }
            
            // 获取商品明细
            List<RetailOutboundItem> items = retailOutboundItemService.lambdaQuery()
                    .eq(RetailOutboundItem::getOutboundId, id)
                    .list();
            retailOutbound.setItems(items);
            
            // 设置商品名称和编码
            for (RetailOutboundItem item : items) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getName());
                    item.setProductCode(product.getBarcode());
                }
                if (retailOutbound.getWarehouseName() != null) {
                    item.setWarehouseName(retailOutbound.getWarehouseName());
                }
            }
        }
        return retailOutbound;
    }
    
    // ==================== 零售退货管理 ====================
    
    /**
     * 分页查询零售退货单
     */
    @GetMapping("/return/page")
    public Page<RetailReturn> getRetailReturnPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String returnNo,
            @RequestParam(required = false) Long outboundId,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Page<RetailReturn> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<RetailReturn> wrapper = Wrappers.lambdaQuery();
        
        if (StringUtils.hasText(returnNo)) {
            wrapper.like(RetailReturn::getReturnNo, returnNo);
        }
        if (outboundId != null) {
            wrapper.eq(RetailReturn::getOutboundId, outboundId);
        }
        if (warehouseId != null) {
            wrapper.eq(RetailReturn::getWarehouseId, warehouseId);
        }
        if (StringUtils.hasText(startDate)) {
            wrapper.ge(RetailReturn::getReturnDate, startDate);
        }
        if (StringUtils.hasText(endDate)) {
            wrapper.le(RetailReturn::getReturnDate, endDate);
        }
        
        wrapper.orderByDesc(RetailReturn::getCreateTime);
        Page<RetailReturn> page1 = retailReturnService.page(page, wrapper);
        List<RetailReturn> records = page1.getRecords();
        
        for (RetailReturn record : records) {
            // 设置仓库名称
            if (record.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(record.getWarehouseId());
                if (warehouse != null) {
                    record.setWarehouseName(warehouse.getName());
                }
            }
            
            // 设置出库单号
            if (record.getOutboundId() != null) {
                RetailOutbound outbound = retailOutboundService.getById(record.getOutboundId());
                if (outbound != null) {
                    record.setOutboundNo(outbound.getOutboundNo());
                }
            }
        }
        
        return page1;
    }
    
    /**
     * 创建零售退货单
     */
    @PostMapping("/return")
    public RetailReturn createRetailReturn(@RequestBody RetailReturn retailReturn) {
        try {
            // 设置创建时间和状态
            retailReturn.setCreateTime(new Date());
            if (retailReturn.getStatus() == null) {
                retailReturn.setStatus(0); // 默认为草稿状态
            }
            
            // 生成零售退货单号
            if (retailReturn.getReturnNo() == null || retailReturn.getReturnNo().isEmpty()) {
                retailReturn.setReturnNo(generateRetailReturnNo());
            }
            
            // 保存零售退货单
            retailReturnService.save(retailReturn);
            
            // 保存商品明细
            if (retailReturn.getItems() != null && !retailReturn.getItems().isEmpty()) {
                for (RetailReturnItem item : retailReturn.getItems()) {
                    item.setReturnId(retailReturn.getId());
                    retailReturnItemService.save(item);
                }
            }
            
            return retailReturn;
        } catch (Exception e) {
            log.error("创建零售退货单失败", e);
            throw new RuntimeException("创建零售退货单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新零售退货单
     */
    @PutMapping("/return")
    public RetailReturn updateRetailReturn(@RequestBody RetailReturn retailReturn) {
        try {
            // 更新零售退货单基本信息
            retailReturnService.updateById(retailReturn);
            
            // 更新商品明细
            if (retailReturn.getItems() != null) {
                // 删除原有明细
                retailReturnItemService.remove(new QueryWrapper<RetailReturnItem>()
                    .eq("return_id", retailReturn.getId()));
                
                // 保存新的明细
                for (RetailReturnItem item : retailReturn.getItems()) {
                    item.setReturnId(retailReturn.getId());
                    retailReturnItemService.save(item);
                }
            }
            
            // 重新查询并返回最新的数据，确保状态等信息正确
            return retailReturnService.getById(retailReturn.getId());
        } catch (Exception e) {
            log.error("更新零售退货单失败", e);
            throw new RuntimeException("更新零售退货单失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除零售退货单
     */
    @DeleteMapping("/return/{id}")
    public boolean deleteRetailReturn(@PathVariable Long id) {
        try {
            // 删除零售退货单明细
            retailReturnItemService.remove(new QueryWrapper<RetailReturnItem>()
                    .eq("return_id", id));
            // 删除零售退货单
            return retailReturnService.removeById(id);
        } catch (Exception e) {
            log.error("删除零售退货单失败", e);
            return false;
        }
    }
    
    /**
     * 完成零售退货单
     */
    @PutMapping("/return/complete/{id}")
    public boolean completeRetailReturn(@PathVariable Long id) {
        try {
            // 获取零售退货单详情
            RetailReturn retailReturn = retailReturnService.getById(id);
            if (retailReturn == null) {
                log.error("零售退货单不存在: {}", id);
                return false;
            }
            
            // 检查零售退货单状态
            if (retailReturn.getStatus() != 1) {
                log.error("零售退货单状态不正确，无法完成: id={}, status={}", id, retailReturn.getStatus());
                return false;
            }
            
            // 获取商品明细
            List<RetailReturnItem> items = retailReturnItemService.lambdaQuery()
                    .eq(RetailReturnItem::getReturnId, id)
                    .list();
            
            if (items == null || items.isEmpty()) {
                log.error("零售退货单没有商品明细: {}", id);
                return false;
            }
            
            // 调整库存（增加库存）
            for (RetailReturnItem item : items) {
                if (!adjustStock(item.getProductId(), retailReturn.getWarehouseId(), item.getQuantity())) {
                    log.error("调整商品库存失败: productId={}, warehouseId={}, quantity={}", 
                        item.getProductId(), retailReturn.getWarehouseId(), item.getQuantity());
                    return false;
                }
            }
            
            // 更新零售退货单状态为已完成
            retailReturn.setStatus(2);
            retailReturnService.updateById(retailReturn);
            
            log.info("零售退货单完成成功: {}", id);
            return true;
        } catch (Exception e) {
            log.error("完成零售退货单失败: {}", id, e);
            return false;
        }
    }
    
    /**
     * 获取零售退货单详情（包含明细）
     */
    @GetMapping("/return/withDetails/{id}")
    public RetailReturn getRetailReturnWithDetails(@PathVariable Long id) {
        RetailReturn retailReturn = retailReturnService.getById(id);
        if (retailReturn != null) {
            // 设置仓库名称
            if (retailReturn.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(retailReturn.getWarehouseId());
                if (warehouse != null) {
                    retailReturn.setWarehouseName(warehouse.getName());
                }
            }
            
            // 设置出库单号
            if (retailReturn.getOutboundId() != null) {
                RetailOutbound outbound = retailOutboundService.getById(retailReturn.getOutboundId());
                if (outbound != null) {
                    retailReturn.setOutboundNo(outbound.getOutboundNo());
                }
            }
            
            // 获取商品明细
            List<RetailReturnItem> items = retailReturnItemService.lambdaQuery()
                    .eq(RetailReturnItem::getReturnId, id)
                    .list();
            retailReturn.setItems(items);
            
            // 设置商品名称和编码
            for (RetailReturnItem item : items) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getName());
                    item.setProductCode(product.getBarcode());
                }
                if (retailReturn.getWarehouseName() != null) {
                    item.setWarehouseName(retailReturn.getWarehouseName());
                }
            }
        }
        return retailReturn;
    }
    
    // ==================== 工具方法 ====================
    
    /**
     * 生成零售出库单号
     */
    private String generateRetailOutboundNo() {
        // 生成格式：LS-YYYYMMDD-XXXX (零售-年月日-4位序号)
        String prefix = "LS";
        String dateStr = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date());
        
        // 查询当天已生成的零售出库单数量，用于生成序号
        LambdaQueryWrapper<RetailOutbound> wrapper = Wrappers.lambdaQuery();
        wrapper.like(RetailOutbound::getOutboundNo, prefix + "-" + dateStr + "-");
        long count = retailOutboundService.count(wrapper);
        
        // 生成4位序号，不足补0
        String sequence = String.format("%04d", count + 1);
        return prefix + "-" + dateStr + "-" + sequence;
    }
    
    /**
     * 生成零售退货单号
     */
    private String generateRetailReturnNo() {
        // 生成格式：LT-YYYYMMDD-XXXX (零售退货-年月日-4位序号)
        String prefix = "LT";
        String dateStr = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date());
        
        // 查询当天已生成的零售退货单数量，用于生成序号
        LambdaQueryWrapper<RetailReturn> wrapper = Wrappers.lambdaQuery();
        wrapper.like(RetailReturn::getReturnNo, prefix + "-" + dateStr + "-");
        long count = retailReturnService.count(wrapper);
        
        // 生成4位序号，不足补0
        String sequence = String.format("%04d", count + 1);
        return prefix + "-" + dateStr + "-" + sequence;
    }
    
    /**
     * 调整库存数量
     */
    private boolean adjustStock(Long productId, Long warehouseId, BigDecimal quantity) {
        try {
            Stock stock = stockService.lambdaQuery()
                .eq(Stock::getProductId, productId)
                .eq(Stock::getWarehouseId, warehouseId)
                .one();

            if (stock != null) {
                BigDecimal newQuantity = stock.getQuantity().add(quantity);
                if (newQuantity.compareTo(BigDecimal.ZERO) < 0) {
                    // 不允许为负，降到0
                    newQuantity = BigDecimal.ZERO;
                }
                stock.setQuantity(newQuantity);
                stock.setTotalAmount(stock.getUnitPrice().multiply(newQuantity));
                stock.setUpdateTime(new Date());
                stockService.updateById(stock);
                return true;
            } else {
                Stock newStock = new Stock();
                newStock.setProductId(productId);
                newStock.setWarehouseId(warehouseId);
                if (quantity.compareTo(BigDecimal.ZERO) > 0) {
                    newStock.setQuantity(quantity);
                } else {
                    // 减少且不存在记录，按0创建
                    newStock.setQuantity(BigDecimal.ZERO);
                }
                newStock.setUnitPrice(BigDecimal.ZERO);
                newStock.setTotalAmount(BigDecimal.ZERO);
                newStock.setCreateTime(new Date());
                newStock.setUpdateTime(new Date());
                stockService.save(newStock);
                return true;
            }
        } catch (Exception e) {
            log.error("库存调整失败: productId={}, warehouseId={}, quantity={}", productId, warehouseId, quantity, e);
            return false;
        }
    }
}
